import React, { FC, useState, useEffect } from "react"
import "./list1.css"
import QuestionCard from "./QuestionCard"
import { produce } from "immer"

const List1 = () => {
  const [count, setCount] = useState(0)
  const increase = () => {
    setCount(count + 1)
  }

  const [list, setList] = useState([
    { id: "q1", title: "问卷1", published: true },
    { id: "q2", title: "问卷2", published: false },
    { id: "q3", title: "问卷3", published: true },
    { id: "q4", title: "问卷4", published: false }
  ])

  const add = () => {
    const obj = {
      id: new Date().getTime().toString(),
      title: "问卷" + (list.length + 1),
      published: false
    }
    setList(
      produce((draft) => {
        draft.push(obj)
      })
    )
  }

  const remove = (id: string) => {
    setList(
      produce((draft) => {
        const index = draft.findIndex((item) => item.id === id)
        draft.splice(index, 1)
      })
    )
  }

  const modify = (id: string) => {
    setList(
      produce((draft) => {
        const result = draft.find((item) => item.id === id)
        if (result) {
          result.published = !result.published
        }
      })
    )
  }

  useEffect(() => {
    console.log("组件加载完成")
    return () => {
      console.log("组件卸载")
      console.log(list)
    }
  }, [])

  return (
    <div className="list1">
      <h1>问卷列表</h1>
      {list.map(({ id, title, published }) => {
        return (
          <QuestionCard
            key={id}
            id={id}
            title={title}
            isPublished={published}
            remove={remove}
            modify={modify}
          />
        )
      })}
      <div>
        <button onClick={add}>添加问卷</button>
      </div>
      <button onClick={increase}>add {count}</button>
    </div>
  )
}

export default List1
